#include "demo_server.h"

#include <boost/thread.hpp>

using boost::asio::io_service;
using namespace boost::asio;

DemoServer::DemoServer() { m_pServer = CreateTCPServerInstance(this); }

DemoServer::~DemoServer() {}

void DemoServer::InitIOS() {
  // 启动ioservices工作线程
  boost::thread t([&]() {
    m_apWork.reset(new io_service::work(m_iosev));
    try {
      boost::system::error_code oErrorCode;
      m_iosev.run(oErrorCode);
      if (oErrorCode) {
        oErrorCode.clear();
      }
    } catch (boost::system::system_error const &ex) {
    } catch (...) {
    }
  });

  // 创建tcp同步应答服务器
  CreateTcpAnsyServer();
}

void DemoServer::CreateTcpAnsyServer() {
  // 端口
  auto port = 4000;

  // 使用线程处理
  boost::thread t([=, this]() {
    // 所有asio类都需要io_service对象
    std::shared_ptr<io_service> piosev(new io_service);
    std::shared_ptr<ip::tcp::acceptor> pAcceptor;
    try {
      pAcceptor.reset(new ip::tcp::acceptor(
          *piosev, ip::tcp::endpoint(ip::tcp::v4(), port)));
    } catch (std::exception ec) {
      // stringstream ss;
      // ss << "前摄器绑定失败，端口疑似被占用！ port:" << port
      //    << ". ec:" << ec.what();
      // SEND_EVENTTRACE(ss.str(), WN_REPORT_LEVEL_ERROR);

      // 属于严重错误，程序直接退出
      exit(-1);
    } catch (...) {
      // stringstream ss;
      // ss << "前摄器绑定失败，端口疑似被占用！ port:" << port << ". ec:"
      //    << "unknown";
      // SEND_EVENTTRACE(ss.str(), WN_REPORT_LEVEL_ERROR);

      // 属于严重错误，程序直接退出
      exit(-1);
    }

    // for (auto i = 0; i < 10; ++i) {
    //   boost::thread t(boost::bind(&CAccountFacade::TcpAnsyAcceptThread, this,
    //                               piosev, pAcceptor));
    // }
  });

  // stringstream ss;
  // ss << "创建同步socketserver成功！监听端口:" << port;
  // SEND_EVENTTRACE(ss.str(), WN_REPORT_LEVEL_INFO);
}

void DemoServer::OnAccept(std::string sessionID, const char *szClientIP,
                          unsigned short usPort) {
  std::cout << " OnAccept:" << sessionID << std::endl;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
int main() {
  DemoServer server;

  for (;;) {
    std::cout << "-" << std::endl;
    ::sleep(1);
    std::cout << "+" << std::endl;
  }

  return 0;
}